/*
 *	TankMania/ServerSocket.java
 *
 *  TankMania/ServerSocket.class
 *
 * (C) 王宏伟 2008010486 计84 清华大学
 * 
 */

/*
 *	ServerTime 
 * 	ServerProtocol
 */

import java.net.*;
import java.io.*;

public class ServerAllSocket
{
	public static Socket socket[] = new Socket[100];
	public static boolean isConnected[] = new boolean[100];
	public static BufferedReader is[] = new BufferedReader[100];
	public static PrintWriter os[] = new PrintWriter[100];
	public static int socketNum = 0;
	public static ServerTime time;
	public static ServerProtocol serverProtocol;
	
	public ServerAllSocket()
	{
		time = new ServerTime();
		int i;
		for(i = 0;i < 100;i++)
			socket[i] = new Socket();
	}
	public static boolean getConnect(int n)
	{
		return isConnected[n];
	}
	public static int getFirst()
	{
		int i;
		for(i = 0;i < 100;i++)
			if(isConnected[i] == false)
				return i;
		return -1;
	}
	public static void setSocket(Socket s)
	{
		int t = getFirst();
		if(t != -1)
		{
			socket[t] = s;
			update();			//Update	isConnected
			sendTime(t);		//Sync Time
		}	
	}
	public static void update()
	{
		int t = 0;
		for(int i = 0;i < 100;i++)
		{
			if(socket[i].isConnected() && !isConnected[i])
			{
				try
				{
					is[i] = new BufferedReader(new InputStreamReader(socket[i].getInputStream()));
					os[i] = new PrintWriter(socket[i].getOutputStream());
				}
				catch(Exception e)
				{
					System.out.println("ServerSocket IO Error! Exit!");
					System.exit(0);
				}
			}
			if(socket[i].isConnected())
			{
				t++;
				isConnected[i] = true;		
			}
			else 
				isConnected[i] = false;
		}
		socketNum = t;
		time.update();
	}
	public static void send(int tankID,String str)
	{
		try{
			os[tankID].println(time.time+" "+str+" ");
			os[tankID].flush();
			String strTemp = new String(str.substring(0,str.indexOf(32)));
			if(!strTemp.equals("sync")&&!strTemp.equals("move-to"))
				System.out.println("Send:"+str);
		}catch(Exception e)
		{
			System.out.println("Send Error!");
			System.exit(0);
		}
	}
	public static void sendTime(int i)
	{
		try{
			os[i].println(time.time+" sync "+time.waitRound+" ");
			os[i].flush();
		}catch(Exception e)
		{	
			System.out.println("Spread Time Error!");
			System.exit(0);
		}		
	}
	public static void spreadTime()
	{	
		int i;
		for(i = 0;i < 100;i++)
		{
			if(getConnect(i))
			{
				sendTime(i);
			}
		}			
	}
	public static void spreadTank(Tank tank,int id)
	{
		spread("create tank "+id+" "+tank.name+" 0 0 "+tank.fullLife+" 0 "+tank.x+" "+tank.y+" "+tank.angle+" "+tank.gunAngle);
	}
	public static void spread(String str)
	{
		System.out.println("Send:"+str);
		int i;
		for(i = 0;i < 100;i++)
		{
			if(getConnect(i))
			{
				try{
					os[i].println(time.time+" "+str+" ");
					os[i].flush();
				}catch(Exception e)
				{	
					System.out.println("Spread Error!");
					System.exit(0);
				}
			}
		}		
	}
	

}
